using System;
using System.IO;
using Microsoft.SmallBasic.Library;
using File = Microsoft.SmallBasic.Library.File;

namespace SmallBasicFun
{
	/// <summary>
	/// This will help you {insert words} into your phrases, text and {other words}
	/// </summary>
	[SmallBasicType]
	public class Parser
	{
		/// <summary>
		/// Merges a template with a list of words. The words to be merged need to be wrapped in {currly braces}
		/// </summary>
		/// <param name="template">The template: "this is a {adjective} template"</param>
		/// <param name="wordList">The wordList:  wordList["simple"] </param>
		/// <returns>The result of merging the template with the word list</returns>
		/// <example>wordList["adjective"] = "smelly"
		/// wordList["bodyPart"] = "butt"
		/// output = Parser.Merge("You have a {adjective} {bodyPart}!", wordList)
		/// </example>
		public static Primitive Merge(Primitive template, Primitive wordList)
		{
			return Parse(template, "{", "}", wordList);
		}

		/// <summary>
		/// The merges a template in the form of a Rich Text File (rtf), usually created using WordPad.
		///  It gives you back the rtf text, which you can display using the Viewer
		/// </summary>
		/// <param name="templateFile">the name of the rtf file (needs the full path)</param>
		/// <param name="wordList">The wordList:  wordList["simple"] </param>
		/// <example>
		/// words["name"] = "Charlie Brown"
		/// rtfContents = Parser.MergeRtfFile("c:\myTemplate.rft", words)
		/// Viewer.DisplayRtfFile(rtfContents)</example>
		/// <returns>The merged output</returns>
		public static Primitive MergeRtfFile(Primitive templateFile, Primitive wordList)
		{
			if (!System.IO.File.Exists(templateFile)) { throw new PlayException("The file {0} is missing.\r\n I can Merge a file that isn't there!", new FileInfo(templateFile).FullName); }
			return Parse(File.ReadContents(templateFile), @"\{", @"\}", wordList);
		}

		private static Primitive Parse(Primitive template, string startCharacter, string endCharacter, Primitive wordList)
		{
			var parsed = "";
			string temp = template;
			var start = temp.IndexOf(startCharacter);
			while (start != -1)
			{
				var end = temp.IndexOf(endCharacter);
				parsed += temp.Substring(0, start);
				var key = temp.Substring(start + startCharacter.Length, end - start - endCharacter.Length);
				string parsed1 = (wordList[key] == null ? "{" + key.ToString() + "}" : "" + wordList[key].ToString());
				parsed += parsed1;
				temp = temp.Substring(end + endCharacter.Length);
				start = temp.IndexOf(startCharacter);
			}

			return parsed+ temp;
		}

	}
}